package com.cloud.elm.service.impl;

import com.cloud.elm.mapper.DeliveryAddressMapper;
import com.cloud.elm.po.DeliveryAddress;
import com.cloud.elm.service.DeliveryAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class DeliveryAddressServiceImpl implements DeliveryAddressService{
	
	@Autowired
	private DeliveryAddressMapper deliveryAddressMapper;

	@Override
	public Integer getLastAddr(String userId) {
		return deliveryAddressMapper.getLastAddr(userId);
	}

	@Override
	public int setLastAddr(String userId, Integer daId) {
		Integer lastDaId = deliveryAddressMapper.getLastAddr(userId);
		if (Objects.isNull(lastDaId)) {
			return deliveryAddressMapper.addLastAddr(userId, daId);
		} else {
			return deliveryAddressMapper.setLastAddr(userId, daId);
		}
	}
	
	@Override
	public List<DeliveryAddress> listDeliveryAddressByUserId(String userId) {
		return deliveryAddressMapper.listDeliveryAddressByUserId(userId);
	}
	
	@Override
	public DeliveryAddress getDeliveryAddressById(Integer daId) {
		return deliveryAddressMapper.getDeliveryAddressById(daId);
	}
	
	@Override
	public int saveDeliveryAddress(DeliveryAddress deliveryAddress) {
		return deliveryAddressMapper.saveDeliveryAddress(deliveryAddress);
	}
	
	@Override
	public int updateDeliveryAddress(DeliveryAddress deliveryAddress) {
		return deliveryAddressMapper.updateDeliveryAddress(deliveryAddress);
	}
	
	@Override
	public void removeDeliveryAddress(Integer daId) {
		DeliveryAddress da = deliveryAddressMapper.getDeliveryAddressById(daId);
		if (Objects.nonNull(da)) {
			deliveryAddressMapper.removeDeliveryAddress(daId);
		}
		if (Objects.nonNull(deliveryAddressMapper.getLastAddr(da.getUserId()))) {
			deliveryAddressMapper.removeLastDeliveryAddress(daId);
		}
	}
}
